package com.heima.wemedia.service.impl;

import com.heima.common.enums.TaskTypeEnum;


import com.heima.leadnews.schedule.IScheduleClient;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.common.ProtostuffUtil;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsTaskService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Date;
@Service
@Slf4j
public class WmNewsTaskServiceImpl implements WmNewsTaskService {
    @Autowired
    IScheduleClient iScheduleClient;
    WmNewsAutoScanService wmNewsAutoScanService;
    @Override

    /**
     * 添加任务到延迟队列中
     * @param id          文章的id，供文章自动审核使用
     * @param publishTime 发布的时间  可以做为任务的执行时间
     */
    @Async
    public void addNewsToTask(Integer id, Date publishTime) {
        log.info("添加任务到延迟服务中----begin");
        Task task = new Task();
        task.setExecuteTime(publishTime.getTime());
        task.setTaskType(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType());
        task.setPriority(TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        WmNews wmNews = new WmNews();
        wmNews.setId(id);
        task.setParameters(ProtostuffUtil.serialize(wmNews));
        iScheduleClient.addTask(task);
        log.info("添加任务到延迟服务中----end");
    }
    /**
     * 消费延迟队列数据
     */
    @Override
    @Scheduled(fixedRate = 50000)
    @SneakyThrows
    public void scanNewsByTask() {
        log.info("文章审核---消费任务执行---begin---");
        //拉取任务
        Task task = iScheduleClient.poll(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType(), TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        if (task != null) {
            byte[] parameters = task.getParameters();
            //反序列化
            WmNews wmNews = ProtostuffUtil.deserialize(parameters, WmNews.class);
            //调用自动审核系统
            Integer id = wmNews.getId();
            wmNewsAutoScanService.autoScanWmNews(id);
        }
        log.info("文章审核---消费任务执行---end---");
    }
}
